/**
 * 需要plus
 */
//保存Storage
window.IMG_KEY = "imgsrc"

/**
 * 拍照和选择图片
 * @param {Object} imgElement 图片元素
 * @param {Object} fn 函数
 */
function CameraPhoto(imgElement, fn) {
	this.imgElement = imgElement;
}

// 拍照
CameraPhoto.prototype.captureImage = function() {
	var cmr = plus.camera.getCamera();
	var res = cmr.supportedImageResolutions[0];
	var fmt = cmr.supportedImageFormats[0];
	var opt = {
		resolution: res,
		format: fmt
	}
	var that = this;
	cmr.captureImage(
		function(path) {
			that.localFileByURL(path)
		},
		function(error) {
			alert("Capture image failed: " + error.message);
		}, opt
	);
};
//相册选择图片
CameraPhoto.prototype.getPhoto = function() {
	var that = this;
	plus.gallery.pick(function(path) {
		var name = path.substring(path.lastIndexOf("/") + 1);
		that.compressImage(path, name); //图片压缩
	}, function(e) {}, {
		filter: 'image'
	});
}
//加载本地图片
CameraPhoto.prototype.localFileByURL = function(path) {
	var that = this;
	plus.io.resolveLocalFileSystemURL(path,
		function(entry) {
			that.compressImage(entry.toLocalURL(), entry.name);
		},
		function(e) {
			plus.nativeUI.toast("读取拍照文件错误：" + e.message);
		});
};

//图片压缩
CameraPhoto.prototype.compressImage = function(url, filename) {
	var name = "_doc/upload/" + filename;
	var that = this;
	plus.zip.compressImage({
			src: url, //src: (String 类型 )压缩转换原始图片的路径
			dst: name, //压缩转换目标图片的路径
			quality: 90, //quality: (Number 类型 )压缩图片的质量.取值范围为1-100
			overwrite: true, //overwrite: (Boolean 类型 )覆盖生成新文件
			width: '250',
			height: '320'
		},
		function(zip) {
			//页面显示图片
			that.showPics(zip.target, name);
		},
		function(error) {
			plus.nativeUI.toast("压缩图片失败，请稍候再试");
		});
};
//图片展示
CameraPhoto.prototype.showPics = function(url, name) {
	//根据路径读取到文件
	var that = this;
	plus.io.resolveLocalFileSystemURL(url,
		function(entry) {
			entry.file(function(file) {
				var fileReader = new plus.io.FileReader();
				fileReader.readAsDataURL(file);
				fileReader.onloadend = function(e) {
					var picUrl = e.target.result.toString();
					that.imgElement.src = picUrl
					//保存图片 base64
					that.setStorageAsync(IMG_KEY, picUrl)
				}
			});
		});
};
// 异步存储键值
CameraPhoto.prototype.setStorageAsync = function(key, picUrl) {
	plus.storage.setItemAsync(key, picUrl, function() {
		mui.toast("设置成功")
	}, function(e) {
		mui.toast("设置失败!" + JSON.stringify(e))
	});
}
//=======================================================================================
/**
 * 打开系统设置
 * @param act 定义Action
 * Android平台 Native.js跳转系统设置各个界面。https://ask.dcloud.net.cn/question/14732
 * iOS平台：用Native.js来写 如何判断系统功能权限是否开启 https://ask.dcloud.net.cn/article/35915
 */
function $plusStartSetting(act) {
	mui.plusReady(function() {
		var main = plus.android.runtimeMainActivity(); //获取activity
		var Intent = plus.android.importClass('android.content.Intent');
		var Settings = plus.android.importClass('android.provider.Settings');
		var intent;
		if (act == "location") {
			intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); //前位置源的配置
		}
		if (act == "app") {
			intent = new Intent(Settings.ACTION_APPLICATION_SETTINGS); //应用程序相关的设置
		}
		if (act == "notify") {
			intent = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS); //消息通知设置
		}
		main.startActivity(intent);
	})
}

//=======================================================================================
/*
    正常权限,无需动态申请:
        ACCESS_LOCATION_EXTRA_COMMANDS
        ACCESS_NETWORK_STATE
        ACCESS_NOTIFICATION_POLICY
        ACCESS_WIFI_STATE
        BLUETOOTH
        BLUETOOTH_ADMIN
        BROADCAST_STICKY
        CHANGE_NETWORK_STATE
        CHANGE_WIFI_MULTICAST_STATE
        CHANGE_WIFI_STATE
        DISABLE_KEYGUARD
        EXPAND_STATUS_BAR
        GET_PACKAGE_SIZE
        INSTALL_SHORTCUT
        INTERNET
        KILL_BACKGROUND_PROCESSES
        MODIFY_AUDIO_SETTINGS
        NFC
        READ_SYNC_SETTINGS
        READ_SYNC_STATS
        RECEIVE_BOOT_COMPLETED
        REORDER_TASKS
        REQUEST_INSTALL_PACKAGES
        SET_ALARM
        SET_TIME_ZONE
        SET_WALLPAPER
        SET_WALLPAPER_HINTS
        TRANSMIT_IR
        UNINSTALL_SHORTCUT
        USE_FINGERPRINT
        VIBRATE
        WAKE_LOCK
        WRITE_SYNC_SETTINGS

    2)危险权限,需要动态申请:
    group:android.permission-group.STORAGE
         READ_EXTERNAL_STORAGE
         WRITE_EXTERNAL_STORAGE

    group:android.permission-group.CONTACTS
         WRITE_CONTACTS
         GET_ACCOUNTS
         READ_CONTACTS

    group:android.permission-group.PHONE
         READ_CALL_LOG
         READ_PHONE_STATE
         CALL_PHONE
         WRITE_CALL_LOG
         USE_SIP
         PROCESS_OUTGOING_CALLS
        com.android.voicemail.permission.ADD_VOICEMAIL

    group:android.permission-group.CALENDAR
         READ_CALENDAR
         WRITE_CALENDAR

    group:android.permission-group.CAMERA
         CAMERA

    group:android.permissiongroup.SENSORS
         BODY_SENSORS

    group:android.permission-group.LOCATION
         ACCESS_FINE_LOCATION
         ACCESS_COARSE_LOCATION

    group:android.permission-group.MICROPHONE
         RECORD_AUDIO

    group:android.permission-group.SMS
         READ_SMS
         RECEIVE_WAP_PUSH
         RECEIVE_MMS
         RECEIVE_SMS
         SEND_SMS
         READ_CELL_BROADCASTS
*/

/**
 * Me:
 *    cnscn <214363570@qq.com>
 *
 * 参考:
 *    https://blog.csdn.net/lvyoujt/article/details/52826556
 *    https://developer.android.com/reference/android/Manifest.permission
 *    https://developer.android.com/reference/android/os/Build.VERSION
 */

function $plusPermissions(act) {
	mui.plusReady(function() {
		var Build = plus.android.importClass("android.os.Build");
		var Manifest = plus.android.importClass("android.Manifest");
		var MainActivity = plus.android.runtimeMainActivity();
		//var context=main.getApplicationContext(); //未用到,在此仅供参考
		//                 Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION
		var ArrPermissions = [
			Manifest.permission.ACCESS_COARSE_LOCATION,
			Manifest.permission.ACCESS_FINE_LOCATION,
			Manifest.permission.READ_EXTERNAL_STORAGE,
			Manifest.permission.WRITE_EXTERNAL_STORAGE,
			Manifest.permission.CAMERA
		];

		function PermissionCheck(permission) {
			if (Build.VERSION.SDK_INT >= 23) {
				if (MainActivity.checkSelfPermission(permission) == -1) {
					return false;
				}
			}
			return true;
		}

		function PermissionChecks(Arr) {
			var HasPermission = true;
			for (var index in Arr) {
				var permission = Arr[index];
				//如果此处没有权限,则是用户拒绝了
				if (!PermissionCheck(permission)) {
					HasPermission = false;
					break;
				}
			}
			return HasPermission;
		}

		function PermissionRequest(Arr) {
			var REQUEST_CODE_CONTACT = 101;
			if (Build.VERSION.SDK_INT >= 23) {
				MainActivity.requestPermissions(Arr, REQUEST_CODE_CONTACT);
			}
		}

		//如果没有权限，则申请
		if (!PermissionChecks(ArrPermissions)) {
			PermissionRequest(ArrPermissions);
		} else {
			//如果拥有权限，那么干点啥吧^_^
			//.......
		}
	})
}
// 申请定位权限
function $plusRequestLocation() {
	mui.plusReady(function() {
		if (plus.os.name == "Android") {
			plus.android.requestPermissions(['android.permission.ACCESS_FINE_LOCATION'], function(e) {
				if (e.deniedAlways.length > 0) { //权限被永久拒绝
					// 弹出提示框解释为何需要定位权限，引导用户打开设置页面开启
					console.log('Always Denied!!! ' + e.deniedAlways.toString());
				}
				if (e.deniedPresent.length > 0) { //权限被临时拒绝
					// 弹出提示框解释为何需要定位权限，可再次调用plus.android.requestPermissions申请权限
					console.log('Present Denied!!! ' + e.deniedPresent.toString());
				}
				if (e.granted.length > 0) { //权限被允许
					//调用依赖获取定位权限的代码
					console.log('Granted!!! ' + e.granted.toString());
				}
			}, function(e) {
				console.log('Request Permissions error:' + JSON.stringify(e));
			});
		}
		if (plus.os.name == "iOS") {
			var cllocationManger = plus.ios.import("CLLocationManager");
			var enable = cllocationManger.locationServicesEnabled();
			var status = cllocationManger.authorizationStatus();
			console.log("enable:" + enable);
			console.log("status:" + status);
			if (enable && status != 2) {
				console.log("手机系统的定位已经打开");
			} else {
				console.log("手机系统的定位没有打开");
			}
			plus.ios.deleteObject(cllocationManger);
		}

	})

}

//=======================================================================================
/**
 * 判断通知权限，打开通知权限(Android部分有问题)
 */
function $plusNotification() {
	mui.plusReady(function() {
		if (plus.os.name == "Android") {
			var main = plus.android.runtimeMainActivity();
			var pkName = main.getPackageName();
			// var NotificationManagerCompat = plus.android.importClass(
			// 	"android.support.v4.app.NotificationManagerCompat");
			//Android部分有问题
			var NotificationManagerCompat = plus.android.importClass("androidx.core.app.NotificationManagerCompat");
			var packageNames = NotificationManagerCompat.from(main);
			console.log(JSON.stringify(packageNames));
			if (packageNames.areNotificationsEnabled()) {
				console.log('已开启通知权限');
				mui.toast('已开启通知权限')
			} else {
				mui.alert('提示', '请先打开APP通知权限', function() {
					var Intent = plus.android.importClass('android.content.Intent');
					var intent = new Intent(
					'android.settings.APP_NOTIFICATION_SETTINGS'); //可设置表中所有Action字段  
					intent.putExtra('android.provider.extra.APP_PACKAGE', pkName);
					main.startActivity(intent);
				});
			}
		}
		if (plus.os.name == "iOS") {
			var UIApplication = plus.ios.import("UIApplication");
			var app = UIApplication.sharedApplication();
			var enabledTypes = 0;
			if (app.currentUserNotificationSettings) {
				var settings = app.currentUserNotificationSettings();
				enabledTypes = settings.plusGetAttribute("types");
			} else {
				//针对低版本ios系统  
				enabledTypes = app.enabledRemoteNotificationTypes();
			}
			plus.ios.deleteObject(app);
			if (0 == enabledTypes) {
				mui.alert('提示', '请先打开APP通知权限', function() {
					var UIApplication = plus.ios.import("UIApplication");
					var NSURL = plus.ios.import("NSURL");
					var setting = NSURL.URLWithString("app-settings:");
					var application = UIApplication.sharedApplication();
					application.openURL(setting);
					plus.ios.deleteObject(setting);
					plus.ios.deleteObject(application);
				});
			}
		}
	})
}


//=======================================================================================
